package com.itheima.bakery.demos.web.controller;

import com.itheima.bakery.demos.web.Repositories.OrderDetailRepository;
import com.itheima.bakery.demos.web.Repositories.OrderRepository;
import com.itheima.bakery.demos.web.model.Order;
import com.itheima.bakery.demos.web.model.OrderDetail;
import com.itheima.bakery.demos.web.service.OrderDetailService;
import com.itheima.bakery.demos.web.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.stream.Collectors;
import java.util.List;
import java.util.Optional;
import java.util.Map;

@RestController
@RequestMapping("/api/orderdetails")
public class OrderDetailController {
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderService orderService;

    private static final Logger logger = LoggerFactory.getLogger(OrderDetailController.class);

    @GetMapping
    public ResponseEntity<List<OrderDetail>> listOrderDetails() {
        List<OrderDetail> orderDetails = orderDetailService.findAllOrderDetails();
        return ResponseEntity.ok(orderDetails);
    }

    @PostMapping
    public ResponseEntity<OrderDetail> createOrderDetail(@RequestBody OrderDetail orderDetail) {
        // 检查是否提供了订单对象
        if (orderDetail.getOrder() == null) {
            // 如果没有提供订单对象，创建一个新的订单
            Order newOrder = new Order();
            // 保存新订单，此时数据库会为自增的orderID赋值
            Order savedOrder = orderService.saveOrder(newOrder);
            // 将保存后的订单对象设置到订单详情中
            orderDetail.setOrder(savedOrder);
        } else {
            // 确保订单详情中的订单ID是有效的
            Order existingOrder = orderRepository.findById(orderDetail.getOrder().getOrderID())
                    .orElseThrow(() -> new RuntimeException("Order not found with ID: " + orderDetail.getOrder().getOrderID()));
            // 设置订单详情中的订单对象
            orderDetail.setOrder(existingOrder);
        }

        // 保存订单详情
        OrderDetail savedOrderDetail = orderDetailService.saveOrderDetail(orderDetail);

        // 返回保存后的订单详情
        return ResponseEntity.ok(savedOrderDetail);
    }

    @GetMapping("/{id}")
    public ResponseEntity<OrderDetail> getOrderDetailById(@PathVariable Integer id) {
        Optional<OrderDetail> orderDetail = orderDetailService.findOrderDetailById(id);
        return orderDetail.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<OrderDetail> updateOrderDetail(@PathVariable Integer id, @RequestBody OrderDetail orderDetail) {
        logger.info("Updating order detail with ID: {}", id);
        OrderDetail existingDetail = orderDetailRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("OrderDetail not found with ID: " + id));

        if (existingDetail == null) {
            return ResponseEntity.notFound().build();
        }

        // 更新订单详情
        existingDetail.setQuantity(orderDetail.getQuantity());
        existingDetail.setUnitPrice(orderDetail.getUnitPrice());

        // 如果需要，更新订单的状态或其他信息
        if (orderDetail.getOrder() != null) {
            Order existingOrder = orderRepository.findById(existingDetail.getOrder().getOrderID())
                    .orElseThrow(() -> new RuntimeException("Order not found with ID: " + existingDetail.getOrder().getOrderID()));
            existingOrder.setStatus(orderDetail.getOrder().getStatus()); // 假设您想更新订单的状态
            orderRepository.save(existingOrder);
        }

        // 保存更新
        OrderDetail updatedDetail = orderDetailRepository.save(existingDetail);
        return ResponseEntity.ok(updatedDetail);
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOrderDetail(@PathVariable Integer id) {
        orderDetailService.deleteOrderDetail(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/stats/product-quantity")
    public ResponseEntity<Map<String, Long>> getProductQuantityStats() {
        List<OrderDetail> allOrderDetails = orderDetailRepository.findAll();
        Map<String, Long> productQuantityMap = allOrderDetails.stream()
                .collect(Collectors.groupingBy(
                        orderDetail -> orderDetail.getProduct().getName(),
                        Collectors.summingLong(OrderDetail::getQuantity) // 使用 summingLong 来确保结果是 Long 类型
                ));

        return ResponseEntity.ok(productQuantityMap);
    }
}